
import { useEffect, useState } from 'react';
import { Upload, Col, Form, Input, Modal, Row, Tabs, Button, Space } from 'antd';
import { TextWidget, getMessage } from '@inbiz/react';
import { request } from '@inbiz/utils';
import './index.less'

const { Dragger } = Upload;

const InsertVideo = (props: any) => {
  const { editor, form, appInfo, videoVisible, videouploadurl, $videoVisible } = props

  const [activePane, $activePane] = useState<'1' | '2'>('1')
  const [autoInsert, $autoInsert] = useState<boolean>(false)
  const [loading, $loading] = useState<boolean>(false)

  useEffect(() => {
    if (videoVisible) {
      $autoInsert(false)
    }
  }, [videoVisible])

  const submit = () => {
    form.validateFields().then((res: any) => {
      const dom: any = editor.selection.getNode()
      if (dom.tagName == 'VIDEO') {
        // 修改
        if (res.src?.trim()) {
          dom.src = res.src
          dom.dataset.mceSrc = res.src
        }
        if (res.width?.trim() != '' && !isNaN(Number(res.width))) {
          dom.width = Number(res.width)
        }
        if (res.height?.trim() != '' && !isNaN(Number(res.height))) {
          dom.height = Number(res.height)
        }
      } else {
        // 插入
        if (res.src?.trim()) {
          const src = res.src?.trim()
          const wid = res.width?.trim() && !isNaN(Number(res.width)) ? Number(res.width) : 300
          const hei = res.height?.trim() && !isNaN(Number(res.height)) ? Number(res.height) : 150
          editor.insertContent(`<video controls="controls" width="${wid}" height="${hei}" src="${src}"></video>`)
        }
      }
      editor.nodeChanged()
      $videoVisible(false)
      $loading(false)
      $activePane('1')
    })
  }

  const srcBlur = (e: any) => {
    if (e.target.value && !autoInsert) {
      $autoInsert(true)
      insertDefaultWidthHeight()
    }
  }

  const widthChange = (e: any) => {
    let val = form?.getFieldsValue(true)
    if (val?.suo?.pick && !isNaN(Number(e.target.value)) && Number(e.target.value)) {
      if (val.suo.num) {
        let hei = Math.round(Number(e.target.value) * val.suo.num)
        form.setFieldValue('height', String(hei))
      } else if (!isNaN(Number(val.height)) && Number(val.height)) {
        form.setFieldValue('suo', {
          pick: true,
          num: Number(val.height) / Number(e.target.value)
        })
      }
    }
  }

  const heightChange = (e: any) => {
    let val = form?.getFieldsValue(true)
    if (val?.suo?.pick && !isNaN(Number(e.target.value)) && Number(e.target.value)) {
      if (val.suo.num) {
        let wid = Math.round(Number(e.target.value) / val.suo.num)
        form.setFieldValue('width', String(wid))
      } else if (!isNaN(Number(val.width)) && Number(val.width)) {
        form.setFieldValue('suo', {
          pick: true,
          num: Number(e.target.value) / Number(val.width)
        })
      }
    }
  }

  const insertDefaultWidthHeight = () => {
    let val = form?.getFieldsValue(true)
    let wid = Number(val.width)
    let hei = Number(val.height)
    let change: boolean = false
    if (!val.width?.trim() || isNaN(Number(val.width))) {
      form.setFieldValue('width', '300')
      wid = 300
      change = true
    }
    if (!val.height?.trim() || isNaN(Number(val.height))) {
      form.setFieldValue('height', '150')
      hei = 150
      change = true
    }
    if (change && val.suo.pick) {
      form.setFieldValue('suo', {
        pick: true,
        num: hei / wid
      })
    }
  }

  const uploadProps = {
    accept: '.mp4,.webm,.ogg',
    showUploadList: false,
    beforeUpload: (file: any) => {
      $loading(true)
      console.log('>>>, upFile:', file.size / 1024 / 1024, file)
      if (/\.(webm|mp4|ogg)$/.test(file.name.toLocaleLowerCase())) {
        if (file.size / 1024 / 1024 <= 100) {
          let formData = new FormData()
          formData.append('file', file)
          formData.append('fileName', file.name)
          // @ts-ignore
          formData.append('notReplaceAppId', true)
          const url = videouploadurl || `/inbiz/api/services/front/engines/v${InbizConfig.API_VERSION}/common/uploadVideoByStaticFile`
          request(url, {
            method: 'POST',
            params: {
              // @ts-ignore
              siteOutId: appInfo?.SiteInfo?.OutId,
              appId: appInfo?.AppId,
              version: InbizConfig.API_VERSION,
            },
            data: formData,
            //@ts-ignore
            requestType: 'formData',
            timeout: 0,
          }).then((res: any) => {
            if (res?.Success && res?.FilePath) {
              const path = res.FilePath?.startsWith?.('/') ? res.FilePath : `/${res.FilePath}`
              form.setFieldValue('src', path)
              insertDefaultWidthHeight()
              $activePane('1')
            }
            $loading(false)
          })
        } else {
          $loading(false)
          // 视频文件必须小于100M
          editor.windowManager.alert(getMessage('Tinymce.video_max_size_message'));
        }
      } else {
        $loading(false)
        // 只支持视频格式：.mp4|.webm|.ogg
        editor.windowManager.alert(getMessage('Tinymce.video_file_types') + '：.mp4|.webm|.ogg');
      }
      return false
    }
  }

  return (
    <>
      <Modal
        title={getMessage('Tinymce.insert_edit_video')} // 插入/编辑视频
        visible={videoVisible}
        width={480}
        wrapClassName={'inbiz-tinymce-custom-inset-video-modal'}
        maskStyle={{ backgroundColor: 'rgba(255,255,255,.75)' }}
        onCancel={() => { $videoVisible(false); $activePane('1'); $loading(false) }}
        destroyOnClose
        footer={null}
      >
        <Tabs tabPosition='left' activeKey={activePane} onChange={(key: any) => $activePane(key)}>
          <Tabs.TabPane key='1' tab={getMessage('Tinymce.ordinary')}> {/* 普通 */}
            <Form form={form} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Row>
                <Form.Item name='src' label={getMessage('Tinymce.address')}>{/* 地址 */}
                  <Input autoComplete="off" onBlur={srcBlur} />
                </Form.Item>
              </Row>
              <Row>
                <Col span={11} style={{ paddingRight: 5 }}>
                  <Form.Item name='width' label={getMessage('Tinymce.width')}>{/* 宽 */}
                    <Input autoComplete="off" onChange={widthChange} />
                  </Form.Item>
                </Col>
                <Col span={11} style={{ paddingRight: 5 }}>
                  <Form.Item name='height' label={getMessage('Tinymce.height')}>{/* 高 */}
                    <Input autoComplete="off" onChange={heightChange} />
                  </Form.Item>
                </Col>
                <Col span={2} className='tiny-suo-btn'>
                  <Form.Item name='suo' label='锁定'>
                    <PickSuo form={form} title={getMessage('Tinymce.suo')} />{/* 保持纵横比 */}
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Tabs.TabPane>
          <Tabs.TabPane key='2' tab={getMessage('Tinymce.upload')}> {/* 上传 */}
            <Dragger {...uploadProps}>
              <div className='tiny-custom-upload-video-deag'>
                <p className="ant-upload-drag-mess">
                  {/* 拖放一个视频到此 */}
                  <TextWidget>Tinymce.red_video_message</TextWidget>
                </p>
                <span className='insert-video-btn'>
                  {/* 浏览视频 */}
                  <TextWidget>Tinymce.red_video</TextWidget>
                </span>
              </div>
            </Dragger>
          </Tabs.TabPane>
        </Tabs>
        <div className='custom-upload-video-footer'>
          <Button
            type='primary'
            onClick={() => { $videoVisible(false); $activePane('1'); $loading(false) }}
          >
            <TextWidget>global.cancel</TextWidget>
          </Button>
          <Button
            type='primary'
            onClick={submit}
          >
            <TextWidget>global.save</TextWidget>
          </Button>
        </div>
        {/* 上传loading遮罩层 */}
        <div className={`tiny-custom-loading ${loading ? 'loading' : ''}`}>
          <div></div>
          <div></div>
          <div></div>
        </div>
      </Modal>
    </>
  )
}

export default InsertVideo

const PickSuo = (props: any) => {
  const { value = { pick: false, num: 0 }, onChange, form, title } = props
  return (
    <span
      className='tiny-custom-suo-btn'
      title={title}
      onClick={() => {
        if (value.pick) {
          onChange?.({ pick: false, num: 0 })
        } else {
          let val = form?.getFieldsValue(true)
          let num = 0
          if (!isNaN(Number(val.width)) && !isNaN(Number(val.height)) && Number(val.width)) {
            num = Number(val.height) / Number(val.width)
          }
          onChange?.({ pick: true, num })
        }
      }}
    >
      {
        value.pick ?
          <svg width="24" height="24" focusable="false"><path d="M16.3 11c.2 0 .3 0 .5.2l.2.6v7.4c0 .3 0 .4-.2.6l-.6.2H7.8c-.3 0-.4 0-.6-.2a.7.7 0 0 1-.2-.6v-7.4c0-.3 0-.4.2-.6l.5-.2H8V8c0-.8.3-1.5.9-2.1.6-.6 1.3-.9 2.1-.9h2c.8 0 1.5.3 2.1.9.6.6.9 1.3.9 2.1v3h.3ZM10 8v3h4V8a1 1 0 0 0-.3-.7A1 1 0 0 0 13 7h-2a1 1 0 0 0-.7.3 1 1 0 0 0-.3.7Z" fillRule="evenodd"></path></svg> :
          <svg width="24" height="24" focusable="false"><path d="M16 5c.8 0 1.5.3 2.1.9.6.6.9 1.3.9 2.1v3h-2V8a1 1 0 0 0-.3-.7A1 1 0 0 0 16 7h-2a1 1 0 0 0-.7.3 1 1 0 0 0-.3.7v3h.3c.2 0 .3 0 .5.2l.2.6v7.4c0 .3 0 .4-.2.6l-.6.2H4.8c-.3 0-.4 0-.6-.2a.7.7 0 0 1-.2-.6v-7.4c0-.3 0-.4.2-.6l.5-.2H11V8c0-.8.3-1.5.9-2.1.6-.6 1.3-.9 2.1-.9h2Z" fillRule="evenodd"></path></svg>
      }
    </span>
  )
}